import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store/store'
import useStore from '@/store'
const { user } = useStore(store)

const modules = import.meta.glob('../views/**/**.vue')
console.log(modules)

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: modules['../views/Layout.vue'],
    children: [
      {
        path: '/',
        component: modules['../views/home/index.vue']
      },
      {
        path: 'category/:id',
        component: modules['../views/category/index.vue']
      },
      {
        path: 'category/sub/:id',
        component: modules['../views/category/sub.vue']
      },
      {
        path: 'product/:id',
        component: modules['../views/goods/index.vue']
      },
      {
        path: 'cart',
        component: modules['../views/cart/index.vue']
      },
      {
        path: 'member/checkout',
        component: modules['../views/member/pay/checkout.vue']
      },
      {
        path: '/member/pay',
        component: modules['../views/member/pay/index.vue']
      }
    ]
  },
  {
    path: '/login',
    component: modules['../views/login/index.vue']
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = user.user
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

export default router
